import {ajax,pAjax} from './gather';

$('.stairs_ol > li').click(function () {
    $('html, body').stop().animate({ scrollTop: $('.stairs_heart > li').eq($(this).index()).offset().top+1 })
  })

  $(window).scroll(function () {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    if(scrollTop <= 470){
        $('.stairs_ol').css({display:'none'})
    }else{
        $('.stairs_ol').css({display:'flex'})

    }
    $('.stairs_heart > li').each(function (index, item) {
      if (scrollTop >= $(item).offset().top) {
        $('.stairs_ol > li').removeClass('active').eq(index).addClass('active')
      }
    })

    if (scrollTop >= 800) {
      $('.stairs_ol > span').stop().animate({ bottom: -30 }, 100)
    } else {
      $('.stairs_ol > span').stop().animate({ bottom: 0 }, 100)
    }
  })
  $('.stairs_ol > span').click(() => $('html, body').animate({ scrollTop: 0 }))



// const id = window.localStorage.getItem('id')
// const token = window.localStorage.getItem('.token')

const cate = document.querySelector('.cate');
const content = document.querySelector('.content');


//
fun();
async function fun() {

  let res = await pAjax({
      url: 'http://localhost:8888/goods/category',
      dataType: 'json',
  })
  // console.log(res)
  let str = "<li class= 'active'>食品酒水</li>"
  let a =res.list.slice(0,5);
  // console.log(a)
  a.forEach(item => {
      str += `
          <li>${item}</li>
      `
  })
  cate.innerHTML = str;
 
}

let yong = {
  current:1,
  pagesize: 60,
  search: '',
  filter: '',
  saleType: 10,
  sortType: 'id',
  sortMethod: 'ASC',
  category: '食品酒水'
}
//商品
showPlay()
async function showPlay() {

    let res = await pAjax({
        url: 'http://localhost:8888/goods/list',
        data: yong,
        dataType: 'json',
    })
    let str = '';
    res.list.forEach(item => {
        str += `
            <li data-id=${item.goods_id}>
                <div class="show">
                    <img data-src="${item.img_big_logo}" alt="">
                </div>
                <div class="info">
                    <p class="title">${item.title}</p>
                    <p class="price">
                        <span class="current">￥${item.current_price}</span>
                        <span class="old">￥${item.price}</span>
                    </p>
                </div>
            </li>
        `
    })
    content.innerHTML = str
    useLazy()
}
function useLazy(){
    var images = document.querySelectorAll(".show img");
    // console.log( images );
    new LazyLoad( images );
    // jQuery 语法 :
    // $(".show img").lazyload();      
}

//点击
play();
function play() {
    //商城
    cate.addEventListener('click', e => {
        let target = e.target;
        if (target.nodeName === 'LI') {
            document.querySelector('.cate .active').classList.remove('active');
            target.classList.add('active')
        }
        yong.category = target.innerText === '全部' ? '' : target.innerText
        yong.current = 1
        console.log(yong.category)
        showPlay()
    })
    
    


   
    


    content.addEventListener('click', e => {
        e = e || window.event
        let target = e.target || e.srcElement
        console.log(target);
        // 判断点击的元素
        if (target.nodeName === 'LI') {

            // 问题:
            // 详情页怎么知道你是点击的那个商量来的
            // 首先要把我的商品的id 保存的到浏览器中
            // 我要使用那个保存
            // 这里我们最好是使用会话存储
            window.sessionStorage.setItem('goodsId', target.dataset.id)
            // 去到详情页面
            window.location.href = './detail.html'

        }
        if (target.nodeName === 'BUTTON') {
            // 我们要加入购物车
            // 必须是要保存你现在是登录状态才能加入到购物车
            addCart(target.dataset.id)
        }
    })

    



}




async function addCart(goodsId) {
    // 首先要回去奥id和token
    let id = window.localStorage.getItem('id')
    let token = window.localStorage.getItem('token')
    // 判断id和token
    if (!id || !token) {
        // 按照我们以前的思路就是去到登录页面 去登录
        // 我现在在的也面是商品列表页面
        // 让用户有一个选择的过程
        if (window.confirm('您还没有登录点取消留在本页面,点击确定去到登录页面')) {
            window.location.href = './login.html'
            return
        }
    }

    // 发送请求
    let res = await pAjax({
        url: 'http://localhost:8888/cart/add',
        method: 'post',
        data: { id, goodsId },
        dataType: 'json',
        headers: { authorization: token }
    })
    console.log(res);

    // 判断code是不是等于1
    if (res.code !== 1) {
        if (window.confirm('您还没有登录点取消留在本页面,点击确定去到登录页面')) {
            window.location.href = './login.html'
            return
        }
    }
    alert('恭喜您添加成功')
}


(function (root, factory) {
    if (typeof exports === "object") {
        module.exports = factory(root);
    } else if (typeof define === "function" && define.amd) {
        define([], factory);
    } else {
        root.LazyLoad = factory(root);
    }
}) (typeof global !== "undefined" ? global : this.window || this.global, function (root) {

    "use strict";

    if (typeof define === "function" && define.amd){
        root = window;
    }

    const defaults = {
        src: "data-src",
        srcset: "data-srcset",
        selector: ".lazyload",
        root: null,
        rootMargin: "0px",
        threshold: 0
    };

    /**
    * Merge two or more objects. Returns a new object.
    * @private
    * @param {Boolean}  deep     If true, do a deep (or recursive) merge [optional]
    * @param {Object}   objects  The objects to merge together
    * @returns {Object}          Merged values of defaults and options
    */
    const extend = function ()  {

        let extended = {};
        let deep = false;
        let i = 0;
        let length = arguments.length;

        /* Check if a deep merge */
        if (Object.prototype.toString.call(arguments[0]) === "[object Boolean]") {
            deep = arguments[0];
            i++;
        }

        /* Merge the object into the extended object */
        let merge = function (obj) {
            for (let prop in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                    /* If deep merge and property is an object, merge properties */
                    if (deep && Object.prototype.toString.call(obj[prop]) === "[object Object]") {
                        extended[prop] = extend(true, extended[prop], obj[prop]);
                    } else {
                        extended[prop] = obj[prop];
                    }
                }
            }
        };

        /* Loop through each object and conduct a merge */
        for (; i < length; i++) {
            let obj = arguments[i];
            merge(obj);
        }

        return extended;
    };

    function LazyLoad(images, options) {
        this.settings = extend(defaults, options || {});
        this.images = images || document.querySelectorAll(this.settings.selector);
        this.observer = null;
        this.init();
    }

    LazyLoad.prototype = {
        init: function() {

            /* Without observers load everything and bail out early. */
            if (!root.IntersectionObserver) {
                this.loadImages();
                return;
            }

            let self = this;
            let observerConfig = {
                root: this.settings.root,
                rootMargin: this.settings.rootMargin,
                threshold: [this.settings.threshold]
            };

            this.observer = new IntersectionObserver(function(entries) {
                Array.prototype.forEach.call(entries, function (entry) {
                    if (entry.isIntersecting) {
                        self.observer.unobserve(entry.target);
                        let src = entry.target.getAttribute(self.settings.src);
                        let srcset = entry.target.getAttribute(self.settings.srcset);
                        if ("img" === entry.target.tagName.toLowerCase()) {
                            if (src) {
                                entry.target.src = src;
                            }
                            if (srcset) {
                                entry.target.srcset = srcset;
                            }
                        } else {
                            entry.target.style.backgroundImage = "url(" + src + ")";
                        }
                    }
                });
            }, observerConfig);

            Array.prototype.forEach.call(this.images, function (image) {
                self.observer.observe(image);
            });
        },

        loadAndDestroy: function () {
            if (!this.settings) { return; }
            this.loadImages();
            this.destroy();
        },

        loadImages: function () {
            if (!this.settings) { return; }

            let self = this;
            Array.prototype.forEach.call(this.images, function (image) {
                let src = image.getAttribute(self.settings.src);
                let srcset = image.getAttribute(self.settings.srcset);
                if ("img" === image.tagName.toLowerCase()) {
                    if (src) {
                        image.src = src;
                    }
                    if (srcset) {
                        image.srcset = srcset;
                    }
                } else {
                    image.style.backgroundImage = "url('" + src + "')";
                }
            });
        },

        destroy: function () {
            if (!this.settings) { return; }
            this.observer.disconnect();
            this.settings = null;
        }
    };

    root.lazyload = function(images, options) {
        return new LazyLoad(images, options);
    };

    if (root.jQuery) {
        const $ = root.jQuery;
        $.fn.lazyload = function (options) {
            options = options || {};
            options.attribute = options.attribute || "data-src";
            new LazyLoad($.makeArray(this), options);
            return this;
        };
    }

    return LazyLoad;
});